﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml.Serialization;

namespace Projecturo.ProjecturoClient.ViewModel
{
    [Serializable]
    [XmlRoot("ViewModel")]
    public class ViewModelConfigurationItem
    {
        [XmlAttribute("name")]
        public string Name { get; set; }
        [XmlAttribute("modelType")]
        public string ModelType { get; set; }
        [XmlAttribute("viewModelType")]
        public string ViewModelType { get; set; }

        [XmlIgnore]
        public Type ModelTyped
        {
            get
            {
                return Type.GetType(ModelType);
            }
        }

        [XmlIgnore]
        public Type ViewModelTyped
        {
            get
            {
                return Type.GetType(ViewModelType);
            }
        }
    }

    [Serializable]
    public class ViewModelCongigurationItemCollection : Collection<ViewModelConfigurationItem>
    {
        public Type GetViewModelType(string modelType)
        {
            if (Count > 0 && !String.IsNullOrEmpty(modelType))
            {
                // Todo: NullReference when just a name is available
                ViewModelConfigurationItem configItem = this.Where(configurationItem => configurationItem.ModelType != null ? configurationItem.ModelType.Equals(modelType) : configurationItem.Name.Equals(modelType)).First();
                if (configItem != null)
                    return configItem.ViewModelTyped;
            }
            return null;
        }

        public Type GetViewModelType(Type modelType)
        {
            if (Count > 0 && modelType != null)
            {
                ViewModelConfigurationItem configItem = this.Where(configurationItem => configurationItem.ModelType != null ? configurationItem.ModelTyped.AssemblyQualifiedName.Equals(modelType.AssemblyQualifiedName) : configurationItem.Name.Equals(modelType.Name)).First();
                if (configItem != null)
                    return configItem.ViewModelTyped;
            } 
            return null;
        }
    }
}
